package com.moxigua.iotbox.func;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.moxigua.iotbox.R;
import com.moxigua.iotbox.base.BaseActivity;
import com.moxigua.iotbox.base.BaseApplication;
import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.bean.BaseRequest;
import com.moxigua.iotbox.bean.MqttAction;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.func.image.ImageFragment;
import com.moxigua.iotbox.func.manual.ManualFragment;
import com.moxigua.iotbox.func.sensor.SensorFragment;
import com.moxigua.iotbox.func.setting.SettingsActivity;
import com.moxigua.iotbox.util.SPUtils;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {

    @BindView(R.id.viewpager)
    ViewPager mViewpager;
    @BindView(R.id.tab)
    TabLayout mTab;
    @BindView(R.id.iv_setting)
    ImageView mIvSetting;

    List<Fragment> mFragments = new ArrayList<>();
    FragmentPagerAdapter mPagerAdapter;
    String[] mTitles = {"传感器", "电器操作", "图像"};
    @BindView(R.id.iv_online_status)
    ImageView mIvOnlineStatus;
    @BindView(R.id.tv_online_status)
    TextView mTvOnlineStatus;

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mFragments.add(new SensorFragment());
        mFragments.add(new ManualFragment());
        mFragments.add(new ImageFragment());

        mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        mViewpager.setAdapter(mPagerAdapter);
        mTab.setupWithViewPager(mViewpager);
        //当未连接mqtt服务器且存在配置文件的时候连接服务器
        if (!MqttClientHepler.getInstance().isConnect() &&!TextUtils.isEmpty((String) SPUtils.get(Constants.SP_ENDPOINT, "")) && !TextUtils.isEmpty((String) SPUtils.get(Constants.SP_USER, "")) && !TextUtils.isEmpty((String) SPUtils.get(Constants.SP_PASS, ""))) {
            //已有SP配置文件直接启动服务
            startService(new Intent(mContext, MqttService.class));
            showLoadingDialog();
        } else {
            showShortToast("请先配置服务器！");
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        getOnlineStatus();  //检查是否从其他页面回传数据
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(mContext);
        stopService(new Intent(mContext, MqttService.class));
    }

    @OnClick(R.id.iv_setting)
    public void onClick() {
        startActivity(SettingsActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseEvent(BaseEvent event) {
        switch (event.topic) {
            case Constants.TOPIC_NOR_CON_SUC:
                //连接成功，测试在线
                mLoadingDialog.loadSuccess();
                showShortToast("服务器连接成功，正在测试设备是否在线");
                testConnect();  //测试设备在线
                break;
            case Constants.TOPIC_ERR_NOCONFIG:
            case Constants.TOPIC_ERR_CON_FAILD:
                //没有配置文件的情况与连接失败的情况
                mLoadingDialog.loadFailed();
                showShortToast(event.toString());
                break;
            case Constants.TOPIC_SUB_REMOTE:
                String json = event.message.toString();
                if (json.contains("\"Online\"")){
                    setOnlineStatus(true);
                } else if (json.contains("\"OffOnline\"")) {
                    setOnlineStatus(false);
                }
//                Logger.d(json);
                break;
        }
    }

    /**
     * 检查是都已经在线了
     */
    private void getOnlineStatus() {
        if (BaseApplication.isOnline()) {
            setOnlineStatus(true);
        } else {
            setOnlineStatus(false);
        }
    }


    /**
     * 改变在线状态的一些列操作
     * @param isOnline
     */
    private void setOnlineStatus(boolean isOnline) {
        Logger.d("设备状态变化！"+isOnline);
        if (isOnline) {
            mTvOnlineStatus.setText(R.string.online);
            Picasso.with(mContext)
                    .load(R.drawable.yes)
                    .into(mIvOnlineStatus);
            if (!BaseApplication.isOnline()) {
                showShortToast("设备在线");
                BaseApplication.setIsOnline(true);
            }
        } else {
            mTvOnlineStatus.setText(R.string.offline);
            Picasso.with(mContext)
                    .load(R.drawable.no)
                    .into(mIvOnlineStatus);
            showShortToast("设备离线");
            BaseApplication.setIsOnline(false);
        }
    }


    /**
     * 测试设备是否在线
     */
    private void testConnect() {
        MqttAction<BaseRequest,Double> requestOnlineAction = new MqttAction<>();
        requestOnlineAction.setMetric(Constants.METRIC_REQUEST_ONLINE);
        BaseRequest requestOnline = new BaseRequest();
        int randomPacketId = (int) (Math.random() * 10000);
        BaseApplication.setLastPacketId(randomPacketId);
        requestOnline.setPacketID(randomPacketId);
        requestOnline.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID,0));
        requestOnlineAction.setTags(requestOnline);
        requestOnlineAction.setValue(Double.valueOf(0));
        String payload = "[" + new Gson().toJson(requestOnlineAction) + "]";
        Logger.d(payload);
        MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_SET, 1, payload.getBytes());
    }


    class ViewPagerAdapter extends FragmentPagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public int getCount() {
            return mTitles.length;
        }
    }

}
